const net = require("net");
async function portUsed(port) {
  return new Promise((resolve) => {
    let server = net.createServer().listen(port);
    server.on("listening", function () {
      server.close();
      resolve(port);
    });
    server.on("error", function (err) {
      if (err.code == "EADDRINUSE") {
        resolve(err);
      }
    });
  });
}
async function getValidPort(port = 3000, app) {
  let sourcePort = port;
  let check = false;
  while (check == false) {
    const res = await portUsed(port);
    if (res instanceof Error) {
      port++;
    } else {
      check = true;
    }
  }
  if (sourcePort != port) {
    app.log.warn(
      `server port [${sourcePort}] is in use, now using port [${port}]`,
      true
    );
  }
  return port;
}
module.exports = getValidPort;
